<template>
    <div class="documentParse">
        <div class="buttons">
            <el-upload
                    class="upload-demo"
                    ref="upload"
                    multiple
                    drag
                    accept=".doc,.docx"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :on-change="handleChange"
                    :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            </el-upload>
            <el-button @click="analysisWord" style="margin-left: 20px;" size="small" type="success">开始解析图片</el-button>
            <el-button @click="clearTable" style="margin-left: 20px;" size="small">清空</el-button>
        </div>
        <div class="tables">
            <div class="tables-title">
                <span>文件列表</span>
            </div>
            <div style="position: absolute;top: 36px;left: 0;right: 0;bottom: 40px;">
                <el-table
                        :data="tableData1"
                        height="100%"
                        border
                        style="width: 100%;">
                    <el-table-column
                            align="center"
                            prop="name"
                            label="文件名">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            prop="path"
                            label="文件位置">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            label="文件大小">
                        <template slot-scope="scope">
                            <span>{{scope.row.size | fileSizeZh}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            align="center"
                            label="解析状态">
                        <template slot-scope="scope">
                            <span>{{scope.row.status | statusText}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            align="center"
                            prop="createTime"
                            label="文件选取时间">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            width="120"
                            label="操作">
                        <template slot-scope="scope">
                            <el-button
                                    type="danger"
                                    size="mini"
                                    @click="handleDelete(scope.$index, scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>

<script>
    import {handleFile} from "../../util/fileParse";

    //引入textract解析word模块
    //对于docx文件，您可以使用textract，它将从.docx文件中提取文本。
    var fs = require('fs');

    export default {
        data() {
            return {
                tableData: this.$store.getters.getFileDoc,
                tableData1: [],
                fileList: []
            }
        },
        mounted() {
            this.tableData1 = JSON.parse(JSON.stringify(this.tableData));
        },
        filters: {
            statusText(type) {
                if (type == 0) {
                    return "未解析";
                }
                if (type == 1) {
                    return "已解析";
                }
                if (type == 2) {
                    return "解析失败";
                }
            },
            fileSizeZh(size){
                var data = "";
                if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
                    data = size.toFixed(1) + "B";
                } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
                    data = (size / 1024).toFixed(1) + "KB";
                } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
                    data = (size / (1024 * 1024)).toFixed(1) + "MB";
                } else { //其他转化成GB
                    data = (size / (1024 * 1024 * 1024)).toFixed(1) + "GB";
                }
                var sizestr = data + "";
                var len = sizestr.indexOf("\.");
                var dec = sizestr.substr(len + 1, 2);
                if (dec == "00") {//当小数点后为00时 去掉小数部分
                    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
                }
                return sizestr;
            }
        },
        methods: {
            //清空表格
            clearTable() {
                let self = this;
                self.$confirm('此操作将永久清空文件, 是否继续?', '提示', {
                    confirmButtonText: '确 定',
                    cancelButtonText: '取 消',
                    type: 'warning'
                }).then(() => {
                    self.tableData1 = [];
                    self.$nextTick(() => {
                        self.$store.dispatch('setFileDoc', []);
                    })
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //解析word文档
            analysisWord() {
                let self = this;
                let newArray = [];
                self.tableData1.forEach((items, index) => {
                    if (items.status == 0) {
                        newArray.push(items);
                    }
                });
                if (newArray.length <= 0) {
                    self.$message({
                        message: "请先上传文件",
                        type: "warning"
                    });
                    return;
                }

                if (newArray.length > self.$store.getters.getAnalysisNum) {
                    self.$message({
                        message: "解析的文件不能超过" + this.$store.getters.getAnalysisNum + "个",
                        type: "warning"
                    });
                    return;
                }

                newArray.forEach((items, index) => {
                    self.parseWord(items.path, index, newArray);
                });
            },

            async parseWord(path, index, datas) {
                let self = this;
                const content = fs.readFileSync(path);
                handleFile(content, datas.length, datas, index, function (data) {
                    self.tableData1.forEach((items, index) => {
                        data.forEach((item, ind) => {
                            if (items.path == item.path) {
                                items.status = item.status;
                            }
                        });
                    });
                    self.$store.dispatch('setFileDoc', self.tableData1);
                    self.$forceUpdate();
                });
            },

            //删除本地选中的文件
            handleDelete(index, row) {
                let self = this;
                self.tableData1.splice(index, 1);

                self.$nextTick(() => {
                    let newArray = JSON.parse(JSON.stringify(self.tableData1));
                    self.$store.dispatch('setFileDoc', newArray);
                })
            },
            handleChange(file) {
                let self = this;
                let opt = {
                    name: file.raw.name,
                    path: file.raw.path,
                    size: file.raw.size,
                    createTime: self.changeTime(new Date()),
                    status: 0 //0：未解析  1：解析成功   2：解析失败
                };
                let flag = false;

                if (self.tableData1.length > 0) {
                    for (let i = 0; i < self.tableData1.length; i++) {
                        if (opt.path === self.tableData1[i].path) {
                            flag = true;
                        }
                    }
                }

                if (flag) {
                    self.$message({
                        message: "请勿重新上传",
                        type: "warning"
                    });
                    return;
                }
                self.tableData1.push(opt);

                let newArray = JSON.parse(JSON.stringify(self.tableData1));
                self.$store.dispatch('setFileDoc', newArray);
            },
            changeTime(d) {
                let self = this;
                var datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                return datetime;
            }
        }
    }
</script>

<style scoped>
    /deep/ .el-upload-dragger {
        height: 32px !important;
        border: none !important;
    }

    /deep/ .upload-demo {
        display: flex;
        align-items: center;
    }

    /deep/ .el-upload-list {
        display: none;
    }

    .documentParse {
        font-size: 18px;
        font-style: normal;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        position: relative;
        width: 100%;
        height: 100%;
        overflow: auto;
        padding: 40px 30px;
        box-sizing: border-box;
    }

    .buttons {
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    .tables {
        position: absolute;
        top: 92px;
        left: 30px;
        right: 30px;
        bottom: 0;
    }

    .tables-title {
        width: 100%;
        height: auto;
        line-height: 16px;
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 20px;
    }
</style>
